package com.test.http;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HttpClientBase {
	private String m_url   = "";//url地址
	private String m_param = "";//参数
	private String m_data  = "";//返回数据
	private String m_error = "";//错误信息
	
	//发送POST请求
	public boolean post(String url,String param){
		if(url.equals("")){
			return false;
		}
		m_url   = url;
		m_param = param;
		
		return doPost();
	}
	
	//获取返回数据
	public String getData(){
		return m_data;
	}
	
	//获取错误内容
	public String getError(){
		return m_error;
	}
	
	private boolean doPost(){
        URL url;
		try {
			url = new URL(m_url);
			//使用HttpURLConnection打开连接
		    HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
		      
		    //因为这个是post请求,设立需要设置为true
		    urlConn.setDoOutput(true);
		    urlConn.setDoInput(true);
		    // 设置以POST方式
		    urlConn.setRequestMethod("POST");
		    // Post 请求不能使用缓存
		    urlConn.setUseCaches(false);
		    urlConn.setInstanceFollowRedirects(true);
		    // 配置本次连接的Content-type，配置为application/x-www-form-urlencoded的urlConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");  连接，从postUrl.openConnection()至此的配置必须要在connect之前完成，
		    // 要注意的是connection.getOutputStream会隐含的进行connect。
		    urlConn.connect();
		    //DataOutputStream流
		    DataOutputStream out = new DataOutputStream(urlConn.getOutputStream());
		    //要上传的参数
		    //将要上传的内容写入流中
		    out.writeBytes(m_param);
		    //刷新、关闭
		    out.flush();
		    out.close(); 
	    
  		    //得到读取的内容(流)
		    InputStreamReader in = new InputStreamReader(urlConn.getInputStream());
	        // 为输出创建BufferedReader
	        BufferedReader buffer = new BufferedReader(in);
	        String inputLine = null;
	        //使用循环来读取获得的数据
	        while (((inputLine = buffer.readLine()) != null)){
	        //我们在每一行后面加上一个"\n"来换行
	        	m_data += inputLine + "\n";
		    }	    
	 
	        //关闭InputStreamReader
	        in.close();
	        //关闭http连接
	        urlConn.disconnect();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			m_error = "MalformedURLException";
			return false;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			m_error = "IOException";
			return false;
		}
	
		return true;
	}

}
